﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business_Layer;
using DataAccess_Layer;

public partial class MyAdmin_ChungLoaiSP_AM : System.Web.UI.Page
{
    long? tkId = null;
    string tkTen = null;
    string tkIdParamName = "ID";
    string tkTenParamName = "Ten";
    LogAction log = new LogAction();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenXem)
        {
            // xử lý quyền xem
            ((CommandField)gvDSNCC_GiangHang.Columns[0]).ShowDeleteButton = false;
            CommandField dtCmdField = ((CommandField)dtChiTietGiangHang.Fields[dtChiTietGiangHang.Fields.Count - 1]);
            dtCmdField.ShowEditButton = false;
            dtCmdField.ShowInsertButton = false;
            XoaNhieuBUTTON.Visible = false;
        }
        else if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenChinhSua)
        {
            // xử lý quyền chỉnh sửa
        }

        //Tim kiem theo parameter truyen vao theo cu phap: [ID=...] [Ten=...]
        initThamSoTK();

        if (!IsPostBack)
        {
            initTextBox();
        }

        List<int> checkedCheckBoxRowIndex = getCheckedCheckBoxRowIndexes(gvDSNCC_GiangHang);
        initDataSource();
        restoreCheckedCheckBox(checkedCheckBoxRowIndex);

        if ((tkId != null || tkTen != null) && gvDSNCC_GiangHang.Rows.Count == 0)
        {
            lblTBKhongTimThay.Visible = true;
            dtChiTietGiangHang.Visible = false;
        }

        lblThongBaoDTView.Visible = false;
        lblThongBaoGridView.Visible = false;
    }
    private void initThamSoTK()
    {
        tkTen = Request.Params[tkTenParamName];

        if (Request.Params[tkIdParamName] != null)
        {
            tkId = long.Parse(Request.Params[tkIdParamName]);
            tkId = tkId == -1 ? null : tkId;
        }
    }
    private void initTextBox()
    {
        txtTK_ID.Text = (tkId == null) ? txtTK_ID.Text : tkId.ToString();
        txtTK_Ten.Text = (tkTen == null) ? txtTK_Ten.Text : tkTen;
    }
    private List<int> getCheckedCheckBoxRowIndexes(GridView gvDSNCC_GiangHang)
    {
        if (gvDSNCC_GiangHang.Rows.Count == 0)
        {
            return null;
        }

        List<int> rowIndexes = new List<int>();
        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                rowIndexes.Add(r.RowIndex);
            }
        }

        return rowIndexes;
    }
    private void restoreCheckedCheckBox(List<int> checkedCheckBoxRowIndex)
    {
        if (checkedCheckBoxRowIndex == null)
        {
            return;
        }

        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (int rowIndex in checkedCheckBoxRowIndex)
        {
            ((CheckBox)gvDSNCC_GiangHang.Rows[rowIndex].Cells[lastCellIndex].FindControl("checkXoa")).Checked = true;
        }
    }
    private void initDataSource()
    {
        refreshGV();
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.SelectedIndex == -1 ? 0 : gvDSNCC_GiangHang.SelectedIndex;
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }
    private void refreshGV()
    {
        gvDSNCC_GiangHang.DataSource = DataAccess_Layer.ChungLoaiSPDAC.tim(tkId, tkTen);
        gvDSNCC_GiangHang.DataBind();
    }

    protected void btnTimKiem_NCCGH_Click(object sender, EventArgs e)
    {
        string ten = txtTK_Ten.Text.Length == 0 ? null : txtTK_Ten.Text;
        long? Id = (txtTK_ID.Text.Length != 0) ? long.Parse(txtTK_ID.Text) : -1;

        string url = Helper.getCurrentPageName(Request.Url) + "?" + tkIdParamName + "=" + Id;

        if (ten != null) url += "&" + tkTenParamName + "=" + ten;

        Response.Redirect(url);
    }
    protected void XoaNhieuBUTTON_Click(object sender, EventArgs e)
    {
        string ids = "";
        List<long> deletedIDs = new List<long>();
        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                long id = long.Parse(r.Cells[1].Text);
                deletedIDs.Add(id);
                ids += id.ToString() + ", ";
            }
        }

        lblThongBaoGridView.Visible = true;
        lblThongBaoGridView.Text = "Xóa thành công record: " + ids.Substring(0, ids.LastIndexOf(", "));
        //log
        log.TenLoaiCapNhat = "Xóa";
        log.Ngay = DateTime.Now;
        log.TenBang = "Bảng Chủng loại sản phẩm";
        log.TenLoaiDangNhap = "Admin";
        log.TenDangNhap = Helper.getCurrentAdminUserName(Session);
        string logText = "";
        log.DuLieuCu = "record ID:" + ids.Substring(0, ids.LastIndexOf(", "));
        logText = "x";
        log.DuLieuMoi = logText;
        Log_BUS.insert(log);
        //log
        try
        {
            DataAccess_Layer.ChungLoaiSPDAC.delete(deletedIDs);
        }
        catch (System.Exception ex)
        {
            lblThongBaoGridView.Text = "Xóa thất bại!";
        }

        initDataSource();
        dtChiTietGiangHang.DataBind();
    }

    protected void gvDSNCC_GiangHang_SelectedIndexChanged(object sender, EventArgs e)
    {
        refreshDetailViewPageIndex();
    }
    private void refreshDetailViewPageIndex()
    {
        dtChiTietGiangHang.DataBind();
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }
    protected void gvDSNCC_GiangHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        Helper.changeGVPageIndex(gvDSNCC_GiangHang, e.NewPageIndex);
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.Rows.Count > 0 ? 0 : -1;
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }
    protected void dtChiTietGiangHang_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        refreshGV();
        refreshDetailViewPageIndex();
    }
    protected void dtChiTietGiangHang_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        refreshGV();
        Helper.changeGVPageIndex(gvDSNCC_GiangHang, gvDSNCC_GiangHang.PageCount - 1);
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.Rows.Count - 1;

        refreshDetailViewPageIndex();
    }
    protected void LQDSNCC_GiangHang_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = gvDSNCC_GiangHang.DataSource;
    }
    protected void btnUploadForEdit_Click(object sender, EventArgs e)
    {
        FileUpload fu = (FileUpload)dtChiTietGiangHang.FindControl("fuForEdit");
        Label statusLABEL = (Label)dtChiTietGiangHang.FindControl("lblUpdloadForEdit");
        TextBox tb = (TextBox)dtChiTietGiangHang.FindControl("txtUploadForEdit");

        try
        {
            string fullName = "";
            string filename = "images/LoaiSanPham/" + fu.FileName;
            fu.SaveAs(Server.MapPath("~/") + filename);
            fullName = "~/" + filename;
            tb.Text = fullName;
            statusLABEL.Text = "File đã được upload!";
        }
        catch (Exception ex)
        {
            statusLABEL.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
    protected void LQDSNCC_GiangHang_Updating(object sender, LinqDataSourceUpdateEventArgs e)
    {
        lblThongBaoDTView.Visible = true;
        //log
        try
        {
            log.TenLoaiCapNhat = "cập nhật";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng Chủng loại sản phẩm";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.ChungLoaiSP logO = (DataAccess_Layer.ChungLoaiSP)e.OriginalObject;

            log.DuLieuCu = "Tên: " + logO.Ten
                + "..\nHình: " + logO.Hinh
                + "..\nTình trạng: " + logO.DaXoa;
      

            logO = (DataAccess_Layer.ChungLoaiSP)e.NewObject;
            log.DuLieuMoi = "Tên: " + logO.Ten
                + "..\nHình: " + logO.Hinh
                + "..\nTình trạng: " + logO.DaXoa;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        DataAccess_Layer.ChungLoaiSP newOrder = (DataAccess_Layer.ChungLoaiSP)e.NewObject;
        try
        {
            DataAccess_Layer.ChungLoaiSPDAC.update((DataAccess_Layer.ChungLoaiSP)newOrder);
            lblThongBaoDTView.Text = "Cập nhật thành công record có ID là " + newOrder.ID;
        }
        catch (System.Exception ex)
        {
            lblThongBaoDTView.Text = "Cập nhật thất bại record có ID là " + newOrder.ID;
        }

        e.Cancel = true;
    }
    protected void LQDSHoaDon_AM_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {
        //log
        try
        {
            log.TenLoaiCapNhat = "Thêm";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng Chủng loại sản phẩm";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.ChungLoaiSP logO;

            log.DuLieuCu = "X";

            logO = (DataAccess_Layer.ChungLoaiSP)e.Result;
            log.DuLieuMoi = "Tên: " + logO.Ten
                + "..\nHình: " + logO.Hinh
                + "..\nTình trạng: " + logO.DaXoa;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        lblThongBaoDTView.Visible = true;
        DataAccess_Layer.ChungLoaiSP newOrder = (DataAccess_Layer.ChungLoaiSP)e.Result;

        if (e.Exception == null)
        {
            lblThongBaoDTView.Text = "Thêm thành công record có ID là " + newOrder.ID;
            return;
        }

        lblThongBaoDTView.Text = "Thêm thất bại record!";
        e.ExceptionHandled = true;
    }
}